package com.suyeer.basic.bean;

import com.suyeer.basic.util.ConstUtil;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author jun 2018/10/19
 */
public class RSA {
    private String privateKey;
    private String publicKey;

    public RSA() {
        this(ConstUtil.DEFAULT_LENGTH);
    }

    public RSA(int length) {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ConstUtil.KEY_ALGORITHM);
            keyPairGenerator.initialize(length);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            //base64格式公钥
            PublicKey publicKey = keyPair.getPublic();
            this.publicKey = Base64.encodeBase64String(publicKey.getEncoded());

            //base64格式私钥
            PrivateKey privateKey = keyPair.getPrivate();
            this.privateKey = Base64.encodeBase64String(privateKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public String getPublicKey() {
        return publicKey;
    }
}
